/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.adapter.driving.persistence.dict.repository;

import com.lap.auth.adapter.driving.persistence.dict.DictCache;
import com.lap.auth.adapter.driving.persistence.dict.DictTypeConverter;
import com.lap.auth.adapter.driving.persistence.dict.mapper.DictTypeMapper;
import com.lap.auth.adapter.driving.persistence.dict.po.DictTypePo;
import com.lap.auth.domain.dict.DictType;
import com.lap.auth.domain.dict.repository.DictTypeRepository;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class DictTypeRepositoryImpl implements DictTypeRepository {

  private final DictTypeConverter dictTypeConverter;
  private final DictTypeMapper dictTypeMapper;

  @CacheEvict(
      value = {DictCache.DICT},
      allEntries = true)
  @Override
  public Integer save(DictType dictType) {
    DictTypePo dictTypePo = dictTypeConverter.toPo(dictType);
    if (dictType.isNew()) {
      dictTypeMapper.insert(dictTypePo);
      return dictTypePo.getId();
    }
    return dictTypeMapper.updateByPrimaryKey(dictTypePo);
  }

  @CacheEvict(
      value = {DictCache.DICT},
      allEntries = true)
  @Override
  public int deleteById(Integer id) {
    return dictTypeMapper.deleteByPrimaryKey(id);
  }

  @Override
  public Optional<DictType> findById(Integer id) {
    var dictTypePo = dictTypeMapper.selectByPrimaryKey(id);
    return Optional.ofNullable(dictTypeConverter.toDomain(dictTypePo));
  }

  @Override
  public Optional<DictType> findByCode(String code) {
    DictTypePo dictTypePo = dictTypeMapper.selectByCode(code);
    DictType dictType = dictTypeConverter.toDomain(dictTypePo);
    return Optional.ofNullable(dictType);
  }
}
